package com.hua.yuan.ui;

import android.content.Intent;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.hua.yuan.R;
import com.hua.yuan.base.BaseAppActivity;
import com.hua.yuan.ui.adapter.TujiListAdapter;
import com.hua.yuan.ui.data.PictureDataRequest;
import com.hua.yuan.ui.module.ImageItem;
import com.hua.yuan.ui.module.ImageListBean;
import com.hua.yuan.util.ToastUtil;
import com.jet.flowtaglayout.FlowTagLayout;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * 时间：2018/8/20
 * 作者：蓝天
 * 描述：图集搜索
 */
public class ImageSearchActivity extends BaseAppActivity implements TextView.OnEditorActionListener {
    private FlowTagLayout flowTagLayout_history;
    private FlowTagLayout flowTagLayout_hot;
    private TextView tv_cancel;
    private EditText et_search_live;
    private ImageView iv_search_icon;
    private List<ImageItem> searchList;
    private List<String> labelList;
    private TujiListAdapter adapter;
    private ListView listView;

    @Override
    protected int initLayoutId() {
        return R.layout.activity_image_search;
    }

    @Override
    protected void initView() {
        flowTagLayout_history = findViewById(R.id.flowTagLayout_history);

        listView = findViewById(R.id.listView);
        adapter = new TujiListAdapter(this);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                startActivity(new Intent(ImageSearchActivity.this, ImageDetailActivity.class).putExtra("id", adapter.getList().get(i).getAtlas_id()));
            }
        });

        tv_cancel = findViewById(R.id.tv_cancel);
        et_search_live = findViewById(R.id.et_search_live);
        iv_search_icon = findViewById(R.id.iv_search_icon);
        et_search_live.setOnEditorActionListener(this);

        iv_search_icon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String slug = et_search_live.getText().toString().trim();
                if (TextUtils.isEmpty(slug)) {
                    ToastUtil.showLongToast("请输入搜索内容");
                    return;
                }
                search(slug);
            }
        });
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @Override
    protected void initNet() {
        PictureDataRequest.getPictureSearchHistory(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {

                try {
                    JSONObject jsonObject = new JSONObject(response);

                    if (!jsonObject.isNull("errno")) {
                        String code = jsonObject.getString("errno");
                        if ("0".equals(code)) {

                            if (!jsonObject.isNull("data")) {
                                JSONArray dataJson = jsonObject.getJSONArray("data");
                                Gson gson = new Gson();

                                if (searchList == null) {
                                    searchList = new ArrayList<>();
                                }

                                labelList = new ArrayList<>();
                                for (int i = 0; i < dataJson.length(); i++) {
                                    JSONObject hot = dataJson.getJSONObject(i);
                                    ImageItem bean = gson.fromJson(hot.toString(), ImageItem.class);

                                    if (bean != null) {
                                        searchList.add(bean);
                                    }

                                    labelList.add(bean.getTitle());

                                    //添加tag
                                    flowTagLayout_history.addTags(labelList);  // 添加tag的列表，该方法会把之前的tags全部清空
                                    flowTagLayout_history.addTag("Kotlin");  // 在尾部添加一个tag
                                    flowTagLayout_history.addTagOfIndex(2,"自定义view");  // 在指定的位置插入tag，示例为在index为2，也就是第三个位置插入tag

                                    //移除tag
                                    flowTagLayout_history.removeTag();  // 移除尾部tag
                                    flowTagLayout_history.removeTagOfIndex(3);  // 移除指定位置的tag，示例为移除index为3，也就是第四个tag移除

                                }
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });


        flowTagLayout_history.setTagClickListener(new FlowTagLayout.OnTagClickListener() {
            @Override
            public void tagClick(int position) {
                // getChildAt(position)方法在这很实用
                flowTagLayout_history.getChildAt(position).setSelected(!flowTagLayout_history.getChildAt(position).isSelected());
                search(labelList.get(position));
            }
        });
    }

    @Override
    public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
        switch(keyEvent.getAction()){
            case KeyEvent.ACTION_DOWN:
            case EditorInfo.IME_ACTION_SEND:
                String slug = et_search_live.getText().toString().trim();
                if (TextUtils.isEmpty(slug)) {
                    ToastUtil.showLongToast("请输入搜索内容");
                    return true;
                }
                search(slug);
                break;
        }
        return true;
    }

    private void search(String slug) {

        PictureDataRequest.getSearchPictures(slug, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    JSONObject jsonObject = new JSONObject(response);

                    if (!jsonObject.isNull("errno")) {
                        String code = jsonObject.getString("errno");

                        if ("0".equals(code)) {

                            if (!jsonObject.isNull("data")) {

                                Gson gson = new Gson();
                                List<ImageListBean> list = new ArrayList<>();
                                JSONArray dataJson = jsonObject.getJSONArray("data");
                                for (int i = 0; i < dataJson.length(); i++) {

                                    JSONObject object = dataJson.getJSONObject(i);

                                    ImageListBean bean = gson.fromJson(object.toString(), ImageListBean.class);
                                    list.add(bean);
                                }

                                if (list.size() > 0) {
                                    listView.setVisibility(View.VISIBLE);

                                    //刷行数据
                                    if (adapter != null) {
                                        List<ImageListBean> oldList = adapter.getList();

                                        if (oldList == null) {
                                            adapter.setList(list);
                                        } else if (oldList.size() == 0) {
                                            adapter.setList(list);
                                        } else {
                                            oldList.addAll(list);
                                            adapter.setList(oldList);
                                        }

                                        adapter.notifyDataSetChanged();
                                    }
                                }else{
                                    listView.setVisibility(View.GONE);
                                    ToastUtil.showLongToast( "搜索暂无数据");
                                }
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
